package start.demo01.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TalkTask implements Runnable{
    private Socket socket;
    public TalkTask(Socket socket){
        this.socket =socket;
    }

    @Override
    public void run(){
        try(BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))){
            InetAddress address=socket.getInetAddress();
            byte[] bytes = new byte[1024];
            int len;

            String message="你好  这次链接成功了";
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            socket.shutdownOutput();
            StringBuilder sb2 = new StringBuilder();
            //只有当客户端关闭它的输出流的时候，服务端才能取得结尾的-1
            while ((len = reader.read()) != -1) {
                // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb2.append(new String(bytes, 0, len, "UTF-8"));
            }
            System.out.println("get message from "+address.getHostAddress()+": " + sb2);
            socket.close();
        }catch(IOException e){

        }
    }
}
